package com.happy.z_open.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.happy.z_open.config.redis.LettuceRedisConfig;
import com.userService.api.equity.UserRightService;
import com.userService.api.open.OpenOrdersService;
import com.userService.api.user.UserBaseInfoService;
import com.userService.api.user.UserRoleService;
import com.userService.entity.equity.RightInfo;
import com.userService.entity.equity.RightRequest;
import com.userService.entity.open.OpenOrdersEntity;
import com.userService.entity.user.UserBaseInfo;
import com.userService.entity.user.UserInfoRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.commonService.api.dictionary.DictionaryInfoService;
import com.woniu.common.Md5.Md5;
import com.woniu.common.commonUtil.Common;
import com.woniu.common.exception.ExceptionEnum;
import com.woniu.common.response.ApiResponse;
import com.woniu.common.token.TokenUtil;
import com.woniu.common.token.TokenValidate;
import com.woniu.common.xms.XmsHttp;

import lombok.extern.slf4j.Slf4j;

/**
 * 系统用户信息维护控制器
 *
 * @author woniu
 */
@Slf4j
@RestController
@RequestMapping("/systemUser")
public class UserController {


    @Reference
    UserBaseInfoService userBaseInfoService;

    @Reference
    UserRoleService userRoleService;

    @Reference
    OpenOrdersService openOrdersService;

    @Reference
    UserRightService userRightService;

    @Reference
    DictionaryInfoService dictionaryInfoService;

    @Autowired
    RedisTemplate<String, String> stringRedisTemplate;


    /**
     * 用户信息
     * 参数：第三方用户信息标志   手机号  姓名  来源
     *
     * @param userBaseInfo
     * @return
     * @throws InterruptedException
     */
    @SuppressWarnings("rawtypes")
    @PostMapping("/saveOrUpdateUserInfo")
    public ApiResponse saveOrUpdateUserInfo(@RequestBody UserBaseInfo userBaseInfo) throws InterruptedException {
        log.info("第三方用户信息：{}", userBaseInfo);
        Boolean addResult = false;
        // 根据第三方用户信息标识查询是否已存在
        UserInfoRequest condRequest = new UserInfoRequest();
        condRequest.setThirdIdentity(userBaseInfo.getThirdIdentity());
        List<UserBaseInfo> userBaerInfoList = userBaseInfoService.queryInfoByCond(condRequest);
        // 根据手机号查询是否已存在
        UserBaseInfo user = userBaseInfoService.queryInfByPhone(userBaseInfo.getPhone());

        log.info("三方id查询结果：{}", userBaerInfoList);
        log.info("手机号查询结果：{}", user);

        if ((userBaerInfoList == null || userBaerInfoList.size() <= 0) && user == null) {
            log.info("新增用户信息：");
            String userBaseInfoId = String.valueOf(Common.nextPkId());
            userBaseInfo.setInfoId(userBaseInfoId);
            if (StringUtils.isEmpty(userBaseInfo.getUserName())) {
                userBaseInfo.setUserName(userBaseInfo.getPhone());
            }
            userBaseInfo.setPassword(Md5.getMd5String(userBaseInfo.getPhone() + "12345"));
            userBaseInfo.setUserFlag("1");
            userBaseInfo.setSource("04");
            userBaseInfo.setThirdIdentity(userBaseInfo.getThirdIdentity());
            userBaseInfo.setCreatedBy("system");
            userBaseInfo.setCreatedTime(LocalDateTime.now().toString());
            userBaseInfo.setModifiedBy("system");
            userBaseInfo.setModifiedTime(LocalDateTime.now().toString());
            log.info("待新增用户信息：{}", userBaseInfo);
            addResult = userBaseInfoService.save(userBaseInfo);
        } else {

            if ((userBaerInfoList != null && userBaerInfoList.size() > 0) && user == null) {
                log.info("1212：{}");
                addResult =   this.updateUser(userBaseInfo, userBaerInfoList.get(0).getInfoId(), userBaerInfoList.get(0).getUserName());
            }
            if ((userBaerInfoList == null || userBaerInfoList.size() <= 0) && user != null) {
                log.info("22222：{}");

                addResult =  this.updateUser(userBaseInfo, user.getInfoId(), user.getUserName());
            }
            if ((userBaerInfoList != null && userBaerInfoList.size() > 0) && user != null) {
                log.info("3333333：{}",userBaerInfoList.get(0).getInfoId());
                log.info("333444444：{}",user.getInfoId());
                addResult =  this.updateUser(userBaseInfo, user.getInfoId(), user.getUserName());
                if (!userBaerInfoList.get(0).getInfoId().equals(user.getInfoId())) {
                    log.info("444444：{}");
                    userBaseInfo.setThirdIdentity("");
                    userBaseInfo.setPhone(userBaerInfoList.get(0).getPhone());
                    addResult = this.updateUser(userBaseInfo, userBaerInfoList.get(0).getInfoId(), userBaerInfoList.get(0).getUserName());
                }

            }

        }
        // 角色信息
        if (addResult) {
            return ApiResponse.result("SUCCESS");
        } else {
            log.error("新增用户基础信息失败！");
            return ApiResponse.resultMsg(ExceptionEnum.INSERT_OR_UPDATE_FAIL);
        }
    }

    private Boolean updateUser(UserBaseInfo userBaseInfo, String infoId, String userName) {
        userBaseInfo.setModifiedBy("system");
        userBaseInfo.setInfoId(infoId);
        if (StringUtils.isEmpty(userName)) {
            userBaseInfo.setUserName(userBaseInfo.getPhone());
        }
        userBaseInfo.setModifiedTime(LocalDateTime.now().toString());
        userBaseInfo.setThirdIdentity(userBaseInfo.getThirdIdentity());
        return userBaseInfoService.saveOrUpdate(userBaseInfo);
    }


    /**
     * 获取token
     * 根据用户的手机号获取token信息
     *
     * @param phone
     * @return
     * @throws InterruptedException
     */
    @SuppressWarnings("rawtypes")
    @GetMapping("/queryTokenInfo")
    public ApiResponse queryTokenInfo(@RequestParam String phone) throws Exception {
        log.info("获取token：{}", phone);
        // 根据手机号查询是否已存在
        UserInfoRequest condRequest = new UserInfoRequest();
        condRequest.setPhone(phone);
        UserBaseInfo userBaerInfo = userBaseInfoService.queryInfByPhone(phone);
        log.info("根据手机号查询结果：{}", userBaerInfo);
        if (userBaerInfo == null || StringUtils.isEmpty(userBaerInfo.getInfoId())) {
            return ApiResponse.resultMsg(ExceptionEnum.EMPTY_RESULT);
        }
        // 根据用户信息id生成token
        String accessToken = TokenUtil.createToken(userBaerInfo.getInfoId());
        // 结果返回
        return ApiResponse.result(accessToken);
    }


    /**
     * 根据token信息获取用户的权益
     *
     * @param request
     * @return
     * @throws InterruptedException
     */
    @SuppressWarnings({"rawtypes"})
    @GetMapping("/queryUserRights")
    public ApiResponse queryUserRightsToken(HttpServletRequest request) throws InterruptedException {
        log.info("根据token中的用户信息获取用户权益");
        //token验证
        TokenValidate tokenValidate = new TokenValidate();
        Map<String, Object> validateReuslt = tokenValidate.validateToken(request);
        if (!"0000".equals(validateReuslt.get("validateResult"))) {
            return ApiResponse.resultMsg(ExceptionEnum.TOKEN_RANDOM_EMPTY);
        }
        //结果对象
        List<RightInfo> rightsInfoList = new ArrayList<RightInfo>();
        //获取token信息中的用户信息
        log.error("token信息:{}", validateReuslt);

        String currentUserId = validateReuslt.get("tokenParam").toString();
        log.error("token中的用户信息ID:{}", currentUserId);
        if (StringUtils.isEmpty(currentUserId)) {
            log.error("token中的用户信息ID异常！");
            return ApiResponse.resultMsg(ExceptionEnum.TOKEN_RANDOM_EMPTY);
        }
        UserBaseInfo currentUserInfo = userBaseInfoService.queryInfById(currentUserId);
        log.info("当前登录用户信息：{}", currentUserInfo);
        if (currentUserInfo == null || StringUtils.isEmpty(currentUserInfo.getInfoId())) {
            log.error("token中的用户信息！");
            return ApiResponse.resultMsg(ExceptionEnum.TOKEN_RANDOM_EMPTY);
        }
        // 根据用户信息（phone）获取用户权益列表   调用西软---xmsopen.lpscard.xopgetpointinfobyguest
//		XmsHttp xmsHttp = new XmsHttp();
        String response = XmsHttp.queryUserRightList(currentUserInfo.getPhone());
        // 处理西软结果
        JSONObject jsonObject = JSON.parseObject(response);
        log.info("西软结果Json：{}", jsonObject);
        if (!jsonObject.getBoolean("success") || jsonObject.get("results") == null || jsonObject.get("results") == "") {
            log.error("调用西软异常！");
            return ApiResponse.resultMsg(ExceptionEnum.EMPTY_RESULT);
        }
        //把之前的卡信息删掉
        RightRequest requestCond = new RightRequest();
        requestCond.setPhone(currentUserInfo.getPhone());
        List<RightInfo> rightInfos = userRightService.queryUserRightList(requestCond);
        if (rightInfos != null && rightInfos.size() > 0) {
            for (RightInfo info : rightInfos) {
                log.info("待删除的卡是：{}", info.getCardNumber());
                info.setDeleteFlag("1");
                userRightService.saveOrUpdate(info);
            }
        }

        // 处理西软结果
        String responstResult = jsonObject.get("results").toString();
        log.info("西软结果Json--results：{}", responstResult);
        // 结果转数组--每一个对象为一张泰幸福会员卡
        JSONArray jsonArray = JSONArray.parseArray(responstResult);
        log.info("西软返回结果数组：{}", jsonArray);

        //******************临时变量**********************\\
        Date date = new Date();
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        String endTempDate = fmt.format(date);    //当前时间----------用于跟卡的结束时间比较
        RightInfo rightInfo = new RightInfo();  //临时变量----用户权益对象
        String cardNumber = "";            //临时变量----会员卡号
        String endDate = "";            //临时变量----会员卡结束时间
        String cardClass = "";            //卡大类
        JSONArray jsonArrayChild = null;    //	临时变量---会员卡权益列表
        JSONObject jsonObjectChild = null; //	临时变量---会员卡权益
        //遍历处理
        for (int i = 0; i < jsonArray.size(); i++) {
            //临时变量初始化
            cardNumber = "";            //临时变量----会员卡号
            endDate = "";            //临时变量----会员卡结束时间
            cardClass = "";            //卡大类
            jsonArrayChild = null;    //	临时变量---会员卡权益列表
            jsonObjectChild = null; //	临时变量---会员卡权益
            //权益变量初始化
            rightInfo = new RightInfo();
            rightInfo.setInfoId(Common.nextPkId());
            rightInfo.setPhone(currentUserInfo.getPhone());
            rightInfo.setSource("01");
            rightInfo.setCreatedBy(currentUserInfo.getPhone());
            rightInfo.setCreatedTime(LocalDateTime.now().toString());
            rightInfo.setModifiedBy(currentUserInfo.getPhone());
            rightInfo.setModifiedTime(LocalDateTime.now().toString());
            // 数组处理
            jsonObject = JSON.parseObject(jsonArray.get(i).toString());
            log.info("第{}张卡信息：{}", i, jsonArray.get(i).toString());
            //******************卡号*******************************\\
            cardNumber = jsonObject.get("cardno").toString();
            log.info("第{}张卡卡号：{}", i, cardNumber);
            if (!StringUtils.isEmpty(cardNumber)) {
                rightInfo.setCardNumber(cardNumber);
            } else {
                cardNumber = jsonObject.get("sno").toString();
                rightInfo.setCardNumber(cardNumber);
            }
            //******************到期时间*******************************\\
            endDate = jsonObject.get("dep").toString();
            if (endDate.compareTo(endTempDate) < 0) {
                continue;
            }
            rightInfo.setEndDate(endDate);
            //******************卡大类*******************************\\
            cardClass = jsonObject.get("cardclass").toString();
            rightInfo.setCardClass(cardClass);
            //******************卡权益信息*******************************\\
            if (jsonObject.get("subaccnts_p") != null) {
                jsonArrayChild = JSONArray.parseArray(jsonObject.get("subaccnts_p").toString());
            } else {
                jsonArrayChild = JSONArray.parseArray(jsonObject.get("subaccnts_b").toString());
            }
            if (jsonArrayChild == null || jsonArrayChild.size() <= 0) {
                continue;
            }
            //遍历权益数组
            for (int j = 0; j < jsonArrayChild.size(); j++) {
                jsonObjectChild = JSON.parseObject(jsonArrayChild.get(j).toString());
                log.info("会员卡权益：{}", jsonObjectChild);
                if (jsonObjectChild.get("subcode") != null && !StringUtils.isEmpty(jsonObjectChild.get("subcode").toString())) {
                    //新增权益信息
                    rightInfo.setCodeValue(jsonObjectChild.get("subcode").toString());
                    rightInfo.setRightNumber(jsonObjectChild.get("balance").toString());
                    log.info("待保存数据--新增：{}", rightInfo);
                    userRightService.save(rightInfo);
                    if ("TB".equals(rightInfo.getCodeValue())) {
                        rightsInfoList.add(rightInfo);
                    }
                }
            }
        }
        //权益结果推送
        log.info("权益列表：{}", rightsInfoList);
        if (rightsInfoList != null && rightsInfoList.size() > 0) {
            return ApiResponse.result(rightsInfoList);
        } else {
            return ApiResponse.resultMsg(ExceptionEnum.EMPTY_RESULT);
        }
    }

    /**
     * 保存订单信息
     *
     * @param cond
     * @return
     * @throws InterruptedException
     */
    @SuppressWarnings({"rawtypes"})
    @PostMapping("/saveOrUpdateOrderInfo")
    public ApiResponse saveOrUpdateOrderInfo(@RequestBody OpenOrdersEntity cond) throws InterruptedException {
        log.info("第三方订单信息：{}", cond);
        Boolean addResult = false;
        // 根据订单号查询是否已存在
        OpenOrdersEntity condRequest = new OpenOrdersEntity();
        condRequest.setOrderNumber(cond.getOrderNumber());
        List<OpenOrdersEntity> ordersEntities = openOrdersService.queryOrdersList(condRequest);
        log.info("查询结果：{}", ordersEntities);
        if (ordersEntities != null && ordersEntities.size() > 0) {
            OpenOrdersEntity info = ordersEntities.get(0);
            cond.setInfoId(info.getInfoId());
            cond.setModifiedBy(cond.getPhone());
            cond.setModifiedTime(LocalDateTime.now().toString());
            addResult = openOrdersService.saveOrUpdate(cond);
        } else {
            log.info("新增订单信息：");
            String baseInfoId = String.valueOf(Common.nextPkId());
            cond.setInfoId(baseInfoId);
            cond.setCreatedBy(cond.getPhone());
            cond.setCreatedTime(LocalDateTime.now().toString());
            cond.setModifiedBy(cond.getPhone());
            cond.setModifiedTime(LocalDateTime.now().toString());
            log.info("待新增订单信息：{}", cond);
            addResult = openOrdersService.save(cond);
        }
        // 结果
        if (addResult) {
            return ApiResponse.result("SUCCESS");
        } else {
            log.error("保存订单信息失败！");
            return ApiResponse.resultMsg(ExceptionEnum.INSERT_OR_UPDATE_FAIL);
        }
    }

    /**
     * 支付
     *
     * @param cond
     * @return
     * @throws InterruptedException
     */
    @SuppressWarnings({"rawtypes"})
    @PostMapping("/balanceRights")
    public ApiResponse balanceRights(@RequestBody OpenOrdersEntity cond) throws InterruptedException {
        log.info("第三方订单信息：{}", cond);
        Boolean addResult = false;
        //泰宝充值
        XmsHttp xmsHttp = new XmsHttp();
        String response = xmsHttp.balanceRights("高尔夫对接" + cond.getOrderNumber(), cond.getPhone(), cond.getCardNo(), cond.getAmount().toString(), cond.getPointType());
        log.info("西软扣泰宝结果：{}", response);
        JSONObject jsonObject = JSON.parseObject(response);
        Boolean payResult = jsonObject.getBoolean("success");
        log.info("西软支付结果：{}", jsonObject);
        if (payResult) {
            return ApiResponse.result("支付成功");
        } else {
            log.error("扣款失败失败！");
            return ApiResponse.resultMessage("2004", "泰宝操作失败", false);
        }
        //将结果 添加到
    }


}
